﻿using System;
using biz.ritter.javapi.io;
using FlickrNet;
using FlickrNet;

namespace nofs.flickrfs.facade
{
   
public class FlickrAuth : IFlickrAuth 
{
	private Flickr _flickr;
	private AuthStore _authStore;
	
	public FlickrAuth(String apiKey, String sharedSecret, File authsDir) //throws Exception 
    {
		_flickr = new Flickr(apiKey, sharedSecret, new REST());
		if(authsDir != null) {
			_authStore = new FileAuthStore(authsDir);
		}
	}
	
	public FlickrAuth(String apiKey, String sharedSecret) //throws Exception 
        :	this(apiKey, sharedSecret, null)
    {
	
	}
	
	public Auth CreateAuth() //throws Exception 
    {
		return CreateAuth(_flickr, 3, 5000);
	}
	
	public Auth CreateAuth(int maxTries) //throws Exception 
    {
		return CreateAuth(_flickr, maxTries, 5000);
	}
	
	private static Auth CreateAuth(Flickr flickr, int maxTries, int timeout) //throws Exception 
    {
		String frob = flickr.getAuthInterface().getFrob();
		URL authUrl = flickr.getAuthInterface().buildAuthenticationUrl(Permission.READ, frob);
		System.out.println("auth url = " + authUrl.toExternalForm());
		Auth token = null;
		while(token == null && (--maxTries) > 0) {
			try {
				token = flickr.getAuthInterface().getToken(frob);
			} catch(FlickrException fe) {
				if(fe.getMessage().contains("108")) {
					System.out.println("getting token failed... please authorize nofs.flickrfs.");
					System.out.println("auth url = " + authUrl.toExternalForm());
					Thread.sleep(timeout);
				} else {
					throw fe;
				}
			}
		}
		if(token == null) {
			throw new Exception("failed to authenticate with Flickr");
		}
		return token;
	}

	private boolean _contextSet = false;
	private void SetContext(Auth token) {
		if(!_contextSet) {
			RequestContext.getRequestContext().setAuth(token);
			_contextSet = true;
		}
	}
	
	public Auth Authorize() throws Exception {
		return Authorize(3);
	}
	
	public Auth Authorize(int maxTries) throws Exception {
		Auth token;
		if(_authStore == null) {
			token = CreateAuth();
		} else {
			Auth[] storedTokens = _authStore.retrieveAll();
			if(storedTokens != null && storedTokens.length >= 1) {
				token = storedTokens[0];
			} else {
				token = CreateAuth(maxTries);
				_authStore.store(token);
			}
		}
		SetContext(token);
		return token;
	}
	
	public Flickr Service() throws Exception {
		Authorize();
		return _flickr;
	}
}
}
